<template>
    <carTop />
    <div class="carmiddle">
        <!-- show-summary设置为true就会在表格尾部展示合计行 
        使用summary-method并传入一个方法，返回一个数组，这个数组中的各项就会显示在合计行的各列中 -->
        <el-table show-summary ref="carTable" :data="tableData" style="width: 100%" tooltip-effect="dark"
            :summary-method="getSummaries" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="28" />
            <el-table-column label="全选" width="50" />
            <el-table-column property="title" label="商品" width="260">
                <template #default="scope">
                    <div class="commdity"><img :src="scope.row.cover" alt="">
                        <div class="tradeName">{{ scope.row.title}}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column property="physiognomy" label="品相" width="100" />
            <el-table-column property="price" label="单价" width="120">
                <template #default="scope">
                    {{ scope.row.price }}
                </template>
            </el-table-column>
            <el-table-column property="acount" label="数量" width="200">
                <template #default="scope">
                    <el-input-number v-model="scope.row.acount" :step=1 :min=1 />
                </template>
            </el-table-column>
            <el-table-column property="price" label="金额" width="120">
                <template #default="scope">{{(scope.row.price*scope.row.acount).toFixed(2)}} </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <router-link to="" @click="moveBtn">移入收藏</router-link>|
                <div @click="delFn"> 删除</div>
            </el-table-column>
        </el-table>
        <div style="margin-top:0" class="btn">
            <div class="activeBtn">
                <div class="selectAll" @click="toggleSelection(tableData)">全选</div>
                <div class="d1" v-if="display">
                    <div class="item1">批量移入收藏夹</div>
                    <div class="item1" @click="deletData">批量删除</div>
                </div>
                <div class="d2" v-if="display">
                    <div class="item1">已选{{selNum}}件商品<el-icon>
                            <ArrowUp />
                        </el-icon>
                    </div>
                    <div class="item1">合计(不含运费) : <span class="money">￥{{totalPrice}}</span> </div>
                </div>
                <div class="active" @click="activeBtn">
                    <router-link to="/toSettlement">去结算</router-link>
                </div>
            </div>
        </div>
    </div>
    <carBottom />
</template>
<script lang="ts">
import carBottom from '@/components/personal/carBottom.vue';
import carTop from '@/components/personal/carTop.vue';
import { getcommodity, commodityList, delcommodity } from '@/utils/api';
import { defineComponent } from 'vue';
// import { useStore } from "@/stores/cars";
interface User {
    id: number
    title: string
    acount: number
    price: number
    physiognomy: string
    selected: number
}
export default defineComponent({
    data() {
        return {
            tableData: [{
                id: 1,
                cover: 'https://www.kfzimg.com/sw/kfz-cos/kfzimg/cebefbdc/6c4b7e115b2c5785_n.jpg',
                title: '当代文学中的世界文学',
                acount: 1,
                price: 40,
                physiognomy: '全新',
                selected: 1
            },
            ],
            display: false,
            totalPrice: 56.53,
            selNum: 0
        }
    },
    components: { carBottom, carTop },
    methods: {
        toggleSelection(rows: User[]) {
            this.display = !this.display
            if (this.display) {
                this.display = true
            } else {
                this.display = false
            }
            if (rows) {
                rows.forEach(row => {
                    // console.log('row...', row);
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-expect-error
                    this.$refs.carTable.toggleAllSelection(row, undefined)
                })

            }

        },
        activeBtn() {
            let data = this.tableData.filter(item => item.selected === 1).map(item => {
                return {
                    id: item.id,
                    title: item.title,
                    cover: item.cover,
                    acount: item.acount,
                    physiognomy: item.physiognomy,
                    price: item.price,
                }
            })
            // console.log(data)
            commodityList(data).then((res) => {
                console.log(res);

            }).catch(err => {
                console.log(err);
            })
        },
        moveBtn(event: any) {
            event.target.parentElement.parentElement.parentElement.remove()
        },
        //删除
        delFn(event: any) {
            if (!confirm('是否确定删除？')) return;
            this.tableData.forEach(item => {
                delcommodity(item.id).then((res: any) => {
                    console.log(res);
                }).catch(err => {
                    console.log(err);
                })
            })
           event.target.parentElement.parentElement.parentElement.remove()

        },
        deletData(index: any) {
            this.tableData.splice(index)
        },
        //勾选的商品
        handleSelectionChange(val: any) {
            this.display = true
            let ids = [];
            for (let ind in val) {
                ids.push(val[ind].id)
            }
            for (let i in this.tableData) {
                if (ids.indexOf(this.tableData[i].id) != -1) {
                    this.tableData[i].selected = 1;
                } else {
                    this.tableData[i].selected = 0;
                }
            }


        },
        //结算 
        getSummaries(param: { columns: any; data: any }) {
            const { columns, data } = param;
            // console.log("columns....", columns)
            const sums: any[] = [];
            if (columns.length > 0) {
                this.totalPrice = this.tableData
                    .filter((item) => item.selected == 1)
                    .map((row) => row.acount * row.price)
                    .reduce((total, num) => total + num, 0);
            } else {
                this.totalPrice = 0;
            }
            return sums;
        }
    },
    /**
     * 对购物车内的数组进行监听，当它发生变化的时候（数组中有数据添加或者删除时）会执行watch，
     * 对从商品页传递过来的商品数据进行本地存储。*/
    watch: {
        tableData: {
            handler(val) {
                // console.log("val...", val)
               val && localStorage.setItem('infoData', JSON.stringify(val))
               this.selNum = this.tableData
                    .filter((item) => item.selected == 1)
                    .map((row) => row.acount)
                    .reduce((total, num) => total + num, 0);
            },
            deep: true,
            // immediate: true
        }
    },
    mounted() {//created在模板渲染成HTML前调用或者模板编译进路前调用 
        // //获取数据
        let r = localStorage.getItem('infoData')
        if (!r) return;
        let info = JSON.parse(r)
        if (info) {
            this.tableData = info;
        }
        let id = this.$route.query.id as unknown as number
        // console.log(id);
        if (id) {
            getcommodity(id).then((res) => {
                console.log(res.data);
                let resdata = res.data.data
                let isHave = -1
                //判断某商品是否存在
                if (res.data.code === 1) {
                    for (let i = 0; i < this.tableData.length; i++) {
                        if (this.tableData[i].id == resdata.id) {
                            isHave = i;
                        }
                    }
                    if (isHave > -1) {
                        this.tableData[isHave].acount += 1

                    } else {
                        this.tableData.push(resdata)
                    }
                }

            }).catch(err => {
                console.log(err);

            })
        }


    },



})


</script>
<style lang="scss" scoped >
.el-input-number>.el-input {
    width: 150px;
}

.el-table__inner-wrapper {
    margin-bottom: -18px;
}

.btn {
    font-size: 12px;
    color: #909090;
    height: 50px;
    border: 1px solid #e9e9e9;
    box-shadow: #e9e9e9;
    line-height: 50px;
    cursor: pointer;

}

.activeBtn {
    display: flex;
    justify-content: space-between;
}

.selectAll {
    padding-left: 10px;
    font-weight: bold;
}

.d1 {
    width: 180px;
    display: flex;
    justify-content: space-around;
    color: #666;
    margin-left: -245px;
}

.d2 {
    width: 340px;
    display: flex;
    color: #666;
    justify-content: space-between;
    margin-right: -260px;


}

.money {
    font-weight: 600;
    color: #b8333c;
    font-size: 20px;
}

.active {
    margin-top: 1px;
    height: 48px;
    width: 112px;
    text-align: center;
    line-height: 48px;
    background: #b8333c;
    font-weight: 400;
    font-size: 20px;
    color: #fff;
}


.carmiddle {
    width: 1000px;
    margin: auto;
    background-color: #fff;
}

.cell {
    text-align: center;
    font-size: 12px;
    padding: 0 5px;
}

.el-button {
    height: 20px;
    font-size: 12px;
}
</style>
<style lang="scss" scoped>
img {
    height: 60px;
    width: 60px;
}

.commdity {
    display: flex;
}

.tradeName {
    margin-left: 10px;

}
</style>